package cn.edu.tsinghua.ie.ieFunds.config;

import cn.edu.tsinghua.ie.ieFunds.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.*;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/js/**", "/css/**", "/image/**", "/plugin/**", "/registerPage", "/register", "/loginPage", "/swagger-ui.html", "/swagger-ui.html#/**")
                .permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login")
                //login
                .defaultSuccessUrl("/").failureUrl("/login?error").permitAll()
                .and()
                //cookie
                .rememberMe()
                //cookie validity
                .tokenValiditySeconds(60 * 60 * 24 * 7)
                //cookie private key
                .key("auth")
                .and()
                .logout()
                //logout
                .logoutUrl("/logout")
                //logout url
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService)
                .passwordEncoder(passwordEncoder());
    }
}

